package com.breaktian.assemble.socket.tcp;

import com.breaktian.assemble.socket.callback.ListenTcpCallBack;
import com.breaktian.assemble.socket.task.TcpConnectTask;
import com.breaktian.assemble.socket.util.Utils;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;






/**
 * @author breaktian
 * tcp协议
 * 服务端
 * */
public class TcpServerSocket {

	
	private ServerSocket tcpServerSocket;
	private ExecutorService pool;
	private ListenTcpCallBack listenTcpCallBack;
	private Timer timer;
	private int port;
	private boolean serverRuning = true;
	
	public static final int SEND_TYPE_DATA = 1;
	public static final int SEND_TYPE_UTF = 2;
	public static final int SEND_TYPE_UTF_NO_BACK = 3;
	
	public static long HEAT_BEAT_TIME = 5000;//5秒

	public TcpServerSocket(int port){
		try {
			this.port = port;
			tcpServerSocket = new ServerSocket(port);
			initThreadPool();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 初始化线程池
	 * */
	private void initThreadPool() {
		int size = Runtime.getRuntime().availableProcessors();
		pool = Executors.newFixedThreadPool(size*2);
	}
	
	/**
	 * 开启心跳
	 * */
//	public void startHeartBeat(){
//		Utils.log("开始心跳检查");
//		timer = new Timer();
//		timer.schedule(new TimerTask() {
//			
//			@Override
//			public void run() {
//				Utils.log("心跳检查");
//				try {
//					if(tcpServerSocket==null||tcpServerSocket.isClosed()){
//						Utils.log("心跳检查：重启服务");
//						tcpServerSocket = new ServerSocket(port);
//						listen(ListenTcpCallBack);
//					}
//				} catch (Exception e) {
//					Utils.log("心跳检查出现异常："+e.getMessage());
//					e.printStackTrace();
//				}
//			}
//		}, 0, HEAT_BEAT_TIME);
//		
//	}
	
	
	/**
	 * 关闭心跳
	 * */
//	public void closeHeartBeat(){
//		if(timer!=null) timer.cancel();
//	}
	
	
	private OutputStream mOutputStream;

	/**
	 * 监听连接和消息
	 * */
	public void listen(ListenTcpCallBack call){
		if(tcpServerSocket==null) throw new IllegalStateException("tcpServerSocket为null");
		if(call==null) throw new IllegalStateException("ListenTcpCallBack为null");
		if(serverRuning){
			Utils.log("已经处于监听状态");
			return;
		}
		
		this.listenTcpCallBack = call;
		
		Utils.log("开始监听连接");
		try {
			while(serverRuning){
				Utils.log("循环监听连接");
				Socket s = tcpServerSocket.accept();
				
				mOutputStream = s.getOutputStream();
				
				Utils.log("接收到新的连接");
				pool.execute(new TcpConnectTask(s, listenTcpCallBack));
			}
		} catch (Exception e) {
			Utils.log("出现异常tcpServerSocket："+e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 往socket写数据
	 * @param out
	 */
	public void writData(byte[] out){
		if(mOutputStream == null){
			return;
		}
		try {
			mOutputStream.write(out);
			mOutputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 关闭socket
	 * */
	public void shutDown(){
		Utils.log("关闭服务器");
		if(tcpServerSocket==null) throw new IllegalStateException("tcpServerSocket为null");
		try {
//			closeHeartBeat();
			Utils.log("关闭心跳");
			serverRuning = false;
			Utils.log("退出循环监听连接");
			if(tcpServerSocket!=null) tcpServerSocket.close();
			Utils.log("close tcpServerSocket");
		} catch (IOException e) {
			Utils.log("shutDown出现异常："+e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	
	
	
	
}
